<?php
	error_reporting(E_ALL || ~E_NOTICE);
	$controlerpagenum = 1;
	$pagestart=1;
	$pageend=1;
	$i=1;
	$j=1;   
	$s='';
	$sqlstr='';
	$blank=false;
	$accesstab='';
	$dbResult=array();
	$rowsnum=array();
	$action = ""; //1---get   2---add   3---del   4----view
	$max_file_size = 20000;
	$destination_folder = "pic/";
	$uptypes=array(  
		'image/jpg',  
		'image/jpeg',  
		'image/png',  
		'image/pjpeg',  
		'image/gif',  
		'image/bmp',  
		'image/x-png'  
	);  
	if($_POST['action'])
	{
		$action = $_POST['action'];
	}
	else
	{
		if($_GET['action'])
		{
			$action = $_GET['action'];
		}
		else
		{
			$action = "get";
		}
		
	}

	if($_POST['page'])
	{
		$controlerpagenum = $_POST['page'];
	}
	else
	{
		$controlerpagenum = 1;
	}
     
    $myconn=@mysql_connect("localhost","root","root");
    if(!$myconn)
    {
        die('Could not connect: '.mysql_error());
	    $string = "Can't connect database : ".mysql_error();
        file_put_contents("test.log", $string, FILE_APPEND);
	    return;
    }
    $db_selected=mysql_select_db("dwaccessDB",$myconn);
	if(!$db_selected)
    {
	    die("Can't use database dwaccessDB : ".mysql_error());
        $string = "Can't use database : ".mysql_error();
        file_put_contents("test.log", $string, FILE_APPEND);		
		mysql_close($myconn);
		return;
	}
        
	if($action == "get")
	{
		 if($db_selected)
		{
			$strSql="select COUNT(*) from staffbasesetting;";
			$result=mysql_query($strSql,$myconn);	        
			$rowsnum = mysql_fetch_array($result);
//	        @file_put_contents("test.log", "rowsnum[0]:".$rowsnum[0]."\n", FILE_APPEND);
			if($rowsnum[0]==0)
			{
				$blank = true;
			}
			mysql_free_result($result);
		}else
		{
			die("Can't use database dwaccessDB : ".mysql_error());
			$string = "Can't use database : ".mysql_error();
//            file_put_contents("test.log", $string, FILE_APPEND);
		}		
		
		$pagemax=1;
		$pagemax = (($rowsnum[0]/10.0)-(int)($rowsnum[0]/10.0))>0.?(int)($rowsnum[0]/10.0)+1:(int)($rowsnum[0]/10.0);
		if($pagemax<1) $pagemax=1;
//		$string = "pagemax=".$pagemax."\n";
//	    file_put_contents("test.log", $string, FILE_APPEND);
		if($controlerpagenum>$pagemax) $controlerpagenum=$pagemax;
		$pagestart=10*$controlerpagenum-10;
		$pageend=10;

		 //如果请求的当前页是最后一页，则返回的条目数取余数，否则固定为10；
		if($controlerpagenum == $pagemax)
		{
			$rowsnum[0] = $rowsnum[0]%10;
			if($rowsnum[0] == 0)
			{
				$rowsnum[0] = 10;
			}
		}
		else
		{
			$rowsnum[0] = 10;
		}
	
		$strSql="select skid,staffnum,staffname,cardnum,departmentname,controlerNum,gatenum,periodofvalitystart,periodofvalityend from staffbasesetting limit ".$pagestart.','.$pageend.';';
//        file_put_contents("test.log", "strSql =".$strSql, FILE_APPEND);
		$result=mysql_query($strSql,$myconn);		
//	    @file_put_contents("test.log", "rowsnum[0] =".$rowsnum[0], FILE_APPEND);	    
//		for(i=1;i<=$rowsnum[0];i++)
		while($dbResult = mysql_fetch_array($result))
		{	        
			for($j=1;$j<=9;$j++)
			{			   
				if($i==1 && $j==1)
				{			        
					$accesstab = "{\"nrows\":\"".$rowsnum[0]."\",\"ncols\":\"10\",\"pageMaxium\":\"".$pagemax."\",\"controlerpagenum\":\"".$controlerpagenum."\",\"s0".$i.'_'.($j-1)."\":\"".$dbResult[($j-1)].'"';						
				}else
				{
					$accesstab = $accesstab.",\"s0".$i.'_'.($j-1)."\":\"".$dbResult[($j-1)].'"';
				}
			}
			$i++;			
		}
//    }	
	if(!$blank)
	{
		$accesstab = $accesstab."}";
	}
	else
	{
		$accesstab = "{\"nrows\":\"0\",\"ncols\":\"9\",\"pageMaxium\":\"0\",\"controlerpagenum\":\"0\"}";
	}	
//		    $accesstab = $accesstab."}";
		mysql_free_result($result);
		
		echo $accesstab;
		// exit;
	}
	   
	if($action == "add")
	{
		$staffnum = $_POST["staffnum"];
		$staffname = $_POST["staffname"];
		$cardnum = $_POST["cardnum"];
		$departmentname = $_POST["departmentname"];
		$controlerNum = $_POST["controlerNum"];
//        	$controlerNum = 3;
		$gatenum = $_POST["gateName"];
		$periodofvalitystart = $_POST["periodofvalitystart"];
		$periodofvalityend = $_POST["periodofvalityend"];
		$entrancevalitystart = $_POST["entrancevalitystart"];
		$entrancevalityend = $_POST["entrancevalityend"];
		$limitenrancenum = $_POST["limitenrancenum"];
		$entrancevalitystart = $_POST["leavevalitystart"];
		$entrancevalityend = $_POST["leavevalityend"];
		$limitenrancenum = $_POST["limitleavenum"];
		$staffgender = $_POST["staffgender"];
		$staffage = $_POST["staffage"];
		$picfilename = $_POST["picfilename"];
		$pinfo=pathinfo($picfilename);  
		$picfilename = $destination_folder.$pinfo["basename"];
		
//			file_put_contents("test.log","113:".$controlerNum."\n", FILE_APPEND);
//		   @file_put_contents("test.log","113:".$strSql."\n", FILE_APPEND);
		
//			$dbResult = mysql_fetch_array($result);
		
//			@file_put_contents("test.log", "rowsnum[0]:".$rowsnum[0]."\n", FILE_APPEND);
//			$string = "Can't exec database : ".mysql_error()."  113:".$strSql."\n";
//			file_put_contents("test.log", $string, FILE_APPEND);
//			mysql_free_result($result);
		
//		mysql_free_result($result);
		if($controlerNum==='ALL')
		{					
			$strSql="select distinct controlerNum from gatesetting WHERE controlerNum != 'ALL' ORDER BY lasttime DESC;";
			$result1=mysql_query($strSql,$myconn);	        
			while($dbResult1 = mysql_fetch_array($result1))
			{
				$strSql="select MAX(skid) from staffbasesetting WHERE controlerNum='$dbResult1[0]' AND staffnum='$staffnum';";
				$result=mysql_query($strSql,$myconn);
				$rowsnum = mysql_fetch_array($result);
				mysql_free_result($result);
				if($rowsnum[0]!=0)
				{
					$sqlstr="UPDATE staffbasesetting SET staffname='$staffname',cardnum='$cardnum',departmentname='$departmentname',gatenum='$gatenum',periodofvalitystart='$periodofvalitystart',periodofvalityend='$periodofvalityend',entrancevalitystart='$entrancevalitystart',entrancevalityend='$entrancevalityend',limitenrancenum='$limitenrancenum',leavevalitystart='$leavevalitystart',leavevalityend='$leavevalityend',limitleavenum='$limitleavenum',staffgender='$staffgender',staffage=$staffage,picfilename='$picfilename' WHERE controlerNum='$dbResult1[0]' AND staffnum='$staffnum';"; 					
					$result=mysql_query($sqlstr);
					mysql_free_result($result);	
//						file_put_contents("test.log","12:".$sqlstr."\n", FILE_APPEND);
					if($result)
					{
						echo "<script language=\"JavaScript\">alert('更新成功。');</script><br/>";
//						echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/staffbasesetting.php',5000);</script><br/>";
//						echo "<script language=\"JavaScript\">parent.setTimeout(parent.location.href='/dw/door/staffbasesetting.jsp',5000);</script><br/>";
						echo "<script language=\"JavaScript\">parent.setTimeout(parent.location.href='/door/staffbasesetting.php',5000);</script><br/>";
					}
					else
					{
						echo "<script language=\"JavaScript\">alert('更新失败。');</script><br/>";
						$string = "add fail : ".mysql_error();
						file_put_contents("test.log", $string, FILE_APPEND);
					}
				}else
				{
					$sqlstr="insert into  staffbasesetting (staffnum,staffname,cardnum,departmentname,controlerNum,gatenum,periodofvalitystart,periodofvalityend,entrancevalitystart,entrancevalityend,limitenrancenum,leavevalitystart,leavevalityend,limitleavenum,staffgender,staffage,picfilename) values ('$staffnum','$staffname','$cardnum','$departmentname','$dbResult1[0]','$gatenum','$periodofvalitystart','$periodofvalityend','$entrancevalitystart','$entrancevalityend','$limitenrancenum','$leavevalitystart','$leavevalityend','$limitleavenum','$staffgender',$staffage,'$picfilename');"; 					
					$result=mysql_query($sqlstr);
					mysql_free_result($result);
					if($result)
					{
						echo "<script language=\"JavaScript\">alert('增加成功。');</script><br/>";
//						echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/staffbasesetting.php',5000);</script><br/>";
//						echo "<script language=\"JavaScript\">parent.setTimeout(parent.location.href='/dw/door/staffbasesetting.jsp',5000);</script><br/>";
						echo "<script language=\"JavaScript\">parent.setTimeout(parent.location.href='/door/staffbasesetting.php',5000);</script><br/>";
					}
					else
					{
						echo "<script language=\"JavaScript\">alert('增加失败。');</script><br/>";
						$string = "add fail : ".mysql_error();
						file_put_contents("test.log", $string, FILE_APPEND);
					}		
				}						
			}
			mysql_free_result($result1);
		}else
		{
			$strSql="select MAX(skid) from staffbasesetting WHERE controlerNum='$controlerNum' AND staffnum='$staffnum';";
			$result=mysql_query($strSql,$myconn);
			$rowsnum = mysql_fetch_array($result);
			mysql_free_result($result);
			if($rowsnum[0]!=0)
			{
				$sqlstr="UPDATE staffbasesetting SET staffname='$staffname',cardnum='$cardnum',departmentname='$departmentname',gatenum='$gatenum',periodofvalitystart='$periodofvalitystart',periodofvalityend='$periodofvalityend',entrancevalitystart='$entrancevalitystart',entrancevalityend='$entrancevalityend',limitenrancenum='$limitenrancenum',leavevalitystart='$leavevalitystart',leavevalityend='$leavevalityend',limitleavenum='$limitleavenum',staffgender='$staffgender',staffage=$staffage,picfilename='$picfilename' WHERE controlerNum='$controlerNum' AND staffnum='$staffnum';"; 
//				file_put_contents("test.log","11:".$sqlstr."\n", FILE_APPEND);
				$result=mysql_query($sqlstr);
				if($result)
				{
					echo "<script language=\"JavaScript\">alert('更新成功。');</script><br/>";
//					echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/staffbasesetting.php',5000);</script><br/>";
//					echo "<script language=\"JavaScript\">parent.setTimeout(parent.location.href='/dw/door/staffbasesetting.jsp',5000);</script><br/>";
					echo "<script language=\"JavaScript\">parent.setTimeout(parent.location.href='/door/staffbasesetting.php',5000);</script><br/>";
				}
				else
				{
					echo "<script language=\"JavaScript\">alert('更新失败。');</script><br/>";
					$string = "add fail : ".mysql_error();
					file_put_contents("test.log", $string, FILE_APPEND);
				}
				mysql_free_result($result);
			}else
			{
				$sqlstr="insert into  staffbasesetting (staffnum,staffname,cardnum,departmentname,controlerNum,gatenum,periodofvalitystart,periodofvalityend,entrancevalitystart,entrancevalityend,limitenrancenum,leavevalitystart,leavevalityend,limitleavenum,staffgender,staffage,picfilename) values ('$staffnum','$staffname','$cardnum','$departmentname','$controlerNum','$gatenum','$periodofvalitystart','$periodofvalityend','$entrancevalitystart','$entrancevalityend','$limitenrancenum','$leavevalitystart','$leavevalityend','$limitleavenum','$staffgender',$staffage,'$picfilename');"; 
//					file_put_contents("test.log","11:".$sqlstr."\n", FILE_APPEND);
				$result=mysql_query($sqlstr);
				if($result)
				{
					echo "<script language=\"JavaScript\">alert('增加成功。');</script><br/>";
//					echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/staffbasesetting.php',5000);</script><br/>";
//					echo "<script language=\"JavaScript\">parent.setTimeout(parent.location.href='/dw/door/staffbasesetting.jsp',5000);</script><br/>";
					echo "<script language=\"JavaScript\">parent.setTimeout(parent.location.href='/door/staffbasesetting.php',5000);</script><br/>";
				}
				else
				{
					echo "<script language=\"JavaScript\">alert('增加失败。');</script><br/>";
					$string = "add fail : ".mysql_error();
					file_put_contents("test.log", $string, FILE_APPEND);
				}
				mysql_free_result($result);	
			}							
		}    	
	}
	if($action == "view")
	{
		$skid = $_POST["skid"];
		//echo $skid."\r\n";
		// $skid = $skid["skid"];
		//echo $skid."\r\n";
		$sqlstr="select staffnum,staffname,staffgender,staffage,picfilename from staffbasesetting where skid=$skid"; 
		//mysql_query("SET NAMES utf8"); 
		$result=mysql_query($sqlstr); 
		$item = mysql_fetch_row($result);
		// var_dump($item);
		//"{\"nrows\":\"".$rowsnum[0]."\",\"ncols\":\"5\",\"pageMaxium\":\"".$pagemax."\",
		echo "{\"staffnum\":\"".$item[0]."\",\"staffname\":\"".$item[1]."\",\"staffgender\":\"".$item[2]."\",\"staffage\":\"".$item[3]."\",\"picfilename\":\"".$item[4].'"}';
		//var_dump($result);

	}
	 if($action == "load")
	{
		if (!is_uploaded_file($_FILES["filename"][tmp_name]))  
		//是否存在文件  
		{  
			 echo "图片不存在!";  
			 exit;  
		}  
		 $file = $_FILES["filename"];  
		if($max_file_size < $file["size"])  
		//检查文件大小  
		{  
			echo "文件太大!";  
			exit;  
		}  
	  
		if(!in_array($file["type"], $uptypes))  
		//检查文件类型  
		{  
			echo "文件类型不符!".$file["type"];  
			exit;  
		}  
		if(!file_exists($destination_folder))  
		{  
			mkdir($destination_folder);  
		}  
	  
		$filename=$file["tmp_name"];  
		//echo $filename."\r\n";
		$image_size = getimagesize($filename);  
		$pinfo=pathinfo($file["name"]);  
		$real_filename = $pinfo["basename"];
	   // echo $real_filename."\r\n";
		$ftype=$pinfo['extension'];  
		//$destination = $destination_folder.$real_filename.".".$ftype; 
		$destination = $destination_folder.$real_filename; 
		if (file_exists($destination) )  
		{  
			echo "同名文件已经存在了";  
			exit;  
		}  
	  
		if(!move_uploaded_file ($filename, $destination))  
		{  
			echo "移动文件出错";  
			exit;  
		}  
		//var_dump($result);

	}
	if($action == "del")
	{
		//echo "del:\r\n";
		$delArr = $_POST['arr'];
		//var_dump($delArr);
		foreach($delArr as $ide)
		{ 
			echo $ide."\r\n";
			$exec="delete from staffbasesetting where skid=$ide"; 
			$result=mysql_query($exec); 
			if((mysql_affected_rows()==0) or (mysql_affected_rows==-1)) 
			{ 
				//echo "没有找到记录，或者删除时出错"; 
				exit; 
			} 
			else{ 
				//echo "学生信息已经删除"; 
			}
		} 
	}
	
	if($action == "down")
	{
		//echo "down:\r\n";
		$downArr = $_POST['arr'];
		//var_dump($downArr);
		foreach($downArr as $ide)
		{ 
//	  			echo $ide."\r\n";
			$exec="SELECT * from staffbasesetting where skid=$ide"; 
			$result=mysql_query($exec); 
			if((mysql_affected_rows()==0) or (mysql_affected_rows==-1)) 
			{ 
				//echo "没有找到记录，或者删除时出错"; 
				echo '{"res":"fail"}';
				exit; 
			}else
			{ 
				$item = mysql_fetch_row($result);
				$transid=uuid();
				$cmdstr="{\"trans_id\":\"".$transid."\",\"cmd_code\":\"KQ_UPDATE_USERINFO\",\"idcard\":\"$item[4]\",\"userid\":\"$item[1]\",\"departmentname\":\"$item[1]\",\"name\":\"".$item[2]."\",\"gatenumber\":\"$item[7]\",\"periodofvalitystart\":\"$item[8]\",\"periodofvalityend\":\"$item[9]\",\"picfilename\":\"".$item[12].'"}';					
				@file_put_contents("test.log", "\n cmdstr =".$cmdstr."\n", FILE_APPEND);
				$strSql="INSERT INTO cmdform(controlerNum,transid,cmdstr) VALUES('".$item[6]."','".$transid."','".$cmdstr."');";
				$result=mysql_query($strSql,$myconn);
				mysql_free_result($result);
				@file_put_contents("test.log", "\n strSql =".$strSql."\n", FILE_APPEND);
			}
		}
		echo  '{"res":"success"}';
	}
	mysql_close($myconn);	
//		

    function uuid() 
	{
        if (function_exists('com_create_guid')) 
		{
            return md5(com_create_guid());
        }else 
		{
            mt_srand((double)microtime()*10000);                   //optional for php 4.2.0 and up.
            $charid = md5(uniqid(rand(),true)); 
//            $charid = strtoupper ( md5 ( uniqid ( rand (), true ) ) ); 
//            $hyphen = chr ( 45 );                                          // "-"
//            $uuid = '' .                                                   //chr(123)// "{"
//            substr ( $charid, 0, 8 ) . $hyphen . substr ( $charid, 8, 4 ) . $hyphen . substr ( $charid, 12, 4 ) . $hyphen . substr ( $charid, 16, 4 ) . $hyphen . substr ( $charid, 20, 12 );                                                                           //.chr(125);// "}"
            return $charid;
        }
    }
?>